package com.zho.common.velocity;

import java.io.InputStream;
import java.util.Properties;

import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.ToolManager;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class SpringVelocityTools implements InitializingBean, DisposableBean {
    private static ToolManager manager = null;
    private String toolCfg = "tools.xml";
    private String velocityCfg = "velocity.properties";

    /**
     * @param toolCfg
     *            the toolCfg to set
     */
    public void setToolCfg(String toolCfg) {
        this.toolCfg = toolCfg;
    }

    /**
     * @param velocityCfg
     *            the velocityCfg to set
     */
    public void setVelocityCfg(String velocityCfg) {
        this.velocityCfg = velocityCfg;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() throws Exception {
        if (manager == null) {
            manager = new ToolManager();
            if (toolCfg != null && toolCfg.length() > 0) {
                manager.configure(toolCfg);
            }
        }
        velocityInit();
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.beans.factory.DisposableBean#destroy()
     */
    public void destroy() throws Exception {
    }

    /**
     * 
     * @return
     */
    public static Context createContext() {
        return manager.createContext();
    }

    /**
     * 
     * @throws Exception
     */
    private void velocityInit() throws Exception {
        InputStream io = null;
        try {
            Properties prop = new Properties();
            ClassLoader clazzLoader = Thread.currentThread().getContextClassLoader();
            io = clazzLoader.getResourceAsStream(velocityCfg);
            prop.load(io);

            Velocity.init(prop);
        } finally {
            if (io != null) {
                try {
                    io.close();
                } catch (Exception e) {
                }
            }
        }
    }
}
